/**
 * 招聘需求列表项
 */
import React from 'react';
import { ListItem, Statistic } from '@/molecules';
import { Col, Form, Row, Popover } from 'antd';
import { history, connect } from 'umi'
import AuthComponent from '@/utils/auth/AuthComponent';
import helper from '@/utils/auth/helper';
import { eventTrack } from '@/utils/track';

import { Icon, Link, Operates } from '../components';
import { CHANNEL_CONDITION_FLAG_ENUM } from '../dictionary';
import DemandBrief from './DemandBrief';
import DemandAccept from './DemandAccept';
import DemandAssign from './DemandAssign';
import DemandPublishQuick from './DemandPublishQuick';
import { DemandChangeStatus } from '.';

const { checkCode } = helper;

function DemandItem({ data, onRefresh, user }) {
    const {
        id,
        candidateNum = '0',
        interviewNum = '0',
        hireNum = '0',
        entryNum = '0',
        recruitNums = '0',
        applyNum = '0',
        recruitNumFromTalent = '0',
        innerChannelReleaseNum = '0',
        totalInwardNum = '0',
        outChannelReleaseNum = '0',
        totalOutwardNum = '0',
        recruitCode,
        recruitStatus,
        dutyCode,
        principalEmployeeCode, // 招聘负责人
        launchEmployeeCode, // 招聘发起人
        dutyName,
        organizationCode,
        organizationName,
        companyCode,
        unReadResumeNum,
        releaseInnerChannelNameList, // 已发布内网渠道名称集合
        releaseOutwardChannelNameList // 已发布外网渠道名称集合
    } = data;
    const { employeeCode } = user;
    const showEdit = [principalEmployeeCode, launchEmployeeCode].includes(employeeCode);

    const basePath = {
        pathname: '/office/personnelManagement/recruitment/demand/detail',
        query: {
            id
        }
    };

    const mixinBasePath = (query = {}) => ({
        ...basePath,
        query: {
            ...basePath.query,
            ...query
        }
    });

    const statisticData = [
        {
            label: '需求',
            value: recruitNums,
            disabled: !checkCode('office:recruitment:course:requirement'),
            action: () => {
                eventTrack({
                    eventName: 'personnel_management_recruitment_demand_list_require_click',
                    pageName: 'personnel_management_recruitment',
                    eventProps: {
                        click_context: data.dutyName
                    }
                });
                history.push(mixinBasePath({ activeKey: '1' }));
            }
        },
        {
            label: '简历',
            value: Number(applyNum) + Number(recruitNumFromTalent),
            unReadNum: unReadResumeNum, // 简历未读数量
            recruitStatus, // 招聘需求状态
            action: () => {
                eventTrack({
                    eventName: '',
                    pageName: 'personnel_management_recruitment',
                    eventProps: {
                        click_context: data.dutyName
                    }
                });
                history.push(mixinBasePath({ activeKey: '2' }));
            }
        },
        {
            label: '候选',
            value: candidateNum,
            disabled: !checkCode('office:recruitment:course:candidate'),
            action: () => {
                eventTrack({
                    eventName: 'personnel_management_recruitment_demand_list_candidate_click',
                    pageName: 'personnel_management_recruitment',
                    eventProps: {
                        click_context: data.dutyName
                    }
                });
                history.push(mixinBasePath({ activeKey: '3' }));
            }
        },
        {
            label: '面试',
            value: interviewNum,
            disabled: !checkCode('office:recruitment:course:interview'),
            action: () => {
                eventTrack({
                    eventName: 'personnel_management_recruitment_demand_list_interview_click',
                    pageName: 'personnel_management_recruitment',
                    eventProps: {
                        click_context: data.dutyName
                    }
                });
                history.push(mixinBasePath({ activeKey: '4' }));
            }
        },
        {
            label: '录用',
            value: hireNum,
            disabled: !checkCode('office:recruitment:course:hire'),
            action: () => {
                eventTrack({
                    eventName: 'personnel_management_recruitment_demand_list_offer_click',
                    pageName: 'personnel_management_recruitment',
                    eventProps: {
                        click_context: data.dutyName
                    }
                });
                history.push(mixinBasePath({ activeKey: '5' }));
            }
        },
        {
            label: '入职',
            value: entryNum,
            disabled: !checkCode('office:personnel:progress:entry:historyList'),
            action: () => {
                eventTrack({
                    eventName: 'personnel_management_recruitment_demand_list_entry_click',
                    pageName: 'personnel_management_recruitment',
                    eventProps: {
                        click_context: data.dutyName
                    }
                });
                history.push(mixinBasePath({ activeKey: '5', employStatus: 9 }));
            }
        }
    ];

    const content = (
        <Row type="flex">
            <Col
                xs={24}
                md={24}
                xl={15}
                style={{ cursor: 'pointer', overflow: 'auto hidden', height: 108 }}
                onClick={() => {
                    history.push(basePath);
                }}
            >
                <DemandBrief data={data} showNamePopOver />
            </Col>
            <Col xs={24} md={24} xl={9}>
                <Statistic data={statisticData} showBadge />
                {/* <Row type="flex" justify="end" style={{ height: '100%', minHeight: '64px' }}>
                </Row> */}
            </Col>
        </Row>
    );

    /**
     * 跳转新增简历
     */
    const handleJumpResumeAdd = React.useCallback(() => {
        history.push({
            pathname: '/office/personnelManagement/recruitment/resume/record/apply',
            query: {
                resumeId: id,
                recruitCode,
                dutyCode,
                dutyName,
                organizationCode,
                organizationName,
                companyCode
            }
        });
    }, [id, recruitCode, dutyCode, dutyName, organizationCode, organizationName, companyCode]);

    /**
     * 用于返回可有or可无popover的数字，用于展示渠道发布情况
     * @param {Array} channelArr 已上线渠道数组
     * @param {Number} wrappedNum 外显数字
     */
    const renderPopoverNum = (channelArr = [], wrappedNum) => {
        function getContent(arr) {
            // 用于返回 popover 所需 content
            const maxLength = arr.reduce((max, current) => {
                if (current.length > max) {
                    return current.length;
                }
                return max;
            }, 0);
            return (
                <div style={{ maxHeight: '140px', overflow: 'auto', width: `${maxLength + 1}em` }}>
                    {arr.map(item => (
                        <p key={item}>{item}</p>
                    ))}
                </div>
            );
        }
        if (channelArr.length > 0) {
            // 有列表的情况下返回被popover包裹的组件
            return (
                <Popover content={getContent(channelArr)}>
                    <Link
                        to={{
                            pathname: '/office/personnelManagement/recruitment/channel',
                            query: {
                                recruitCode
                            }
                        }}
                        onClick={() => {
                            eventTrack({
                                eventName: 'personnel_management_recruitment_demand_list_published_channels_click',
                                pageName: 'personnel_management_recruitment',
                                eventProps: {
                                    click_context: data.dutyName
                                }
                            });
                        }}
                    >
                        <strong>{wrappedNum}</strong>
                    </Link>
                </Popover>
            );
        }
        return (
            <Link
                to={{
                    pathname: '/office/personnelManagement/recruitment/channel',
                    query: {
                        recruitCode
                    }
                }}
                onClick={() => {
                    eventTrack({
                        eventName: 'personnel_management_recruitment_demand_list_published_channels_click',
                        pageName: 'personnel_management_recruitment',
                        eventProps: {
                            click_context: data.dutyName
                        }
                    });
                }}
            >
                <strong>{wrappedNum}</strong>
            </Link>
        );
    };

    const renderBtn = () => {
        let arr = [];
        const edit = showEdit ? (
            <AuthComponent code="office:recruitment:course:requirement:edit">
                {[2, 3].includes(recruitStatus) && (
                    <Icon
                        title="编辑"
                        type="listfunction_edit_icon_default"
                        onClick={() => {
                            eventTrack({
                                eventName: 'personnel_management_recruitment_demand_list_edit_click',
                                pageName: 'personnel_management_recruitment',
                                eventProps: {
                                    click_context: data.dutyName
                                }
                            });
                            history.push({
                                pathname: '/office/personnelManagement/recruitment/demand/edit',
                                query: {
                                    recruitCode
                                }
                            });
                        }}
                    />
                )}
            </AuthComponent>
        ) : null;

        if (recruitStatus === 3) {
            arr = [
                <DemandChangeStatus
                    data={data}
                    onSuccess={onRefresh}
                    onClick={() => {
                        eventTrack({
                            eventName: 'personnel_management_recruitment_demand_list_detail_status_update_click',
                            pageName: 'personnel_management_recruitment',
                            eventProps: {
                                click_context: data.dutyName
                            }
                        });
                    }}
                />,
                <DemandAssign
                    data={data}
                    onSuccess={onRefresh}
                    onClick={() => {
                        eventTrack({
                            eventName: 'personnel_management_recruitment_demand_list_xgfzr_click',
                            pageName: 'personnel_management_recruitment',
                            eventProps: {
                                click_context: data.dutyName
                            }
                        });
                    }}
                />
            ];
        } else if (recruitStatus === 2) {
            arr = [
                <DemandAccept data={data} onSuccess={onRefresh} />,
                <DemandAssign data={data} onSuccess={onRefresh} />
            ];
        }
        return (
            <Operates
                operates={[
                    <AuthComponent code="office:recruitment:course:resume:add">
                        <Icon
                            title="录入简历"
                            type="listfunction_readyinterview_icon_default"
                            onClick={() => {
                                eventTrack({
                                    eventName: 'personnel_management_recruitment_demand_list_detail_resume_enter_click',
                                    pageName: 'personnel_management_recruitment',
                                    eventProps: {
                                        click_context: data.dutyName
                                    }
                                });
                                handleJumpResumeAdd();
                            }}
                        />
                    </AuthComponent>,
                    ...arr,
                    <DemandPublishQuick
                        data={data}
                        onSuccess={onRefresh}
                        onClick={() => {
                            eventTrack({
                                eventName: 'personnel_management_recruitment_demand_list_channel_publish_click',
                                pageName: 'personnel_management_recruitment',
                                eventProps: {
                                    click_context: data.dutyName
                                }
                            });
                        }}
                    />,
                    edit
                ]}
            />
        );
    };

    const action = (
        <Row type="flex" justify="space-between" align="middle">
            <Row type="flex">
                <Col style={{ marginRight: 16 }}>
                    申请
                    <Link
                        to={mixinBasePath({ activeKey: '2', notesSourceList: CHANNEL_CONDITION_FLAG_ENUM.EXCLUDE_RCK })}
                        onClick={() => {
                            eventTrack({
                                eventName: 'personnel_management_recruitment_demand_list_apply_num_click',
                                pageName: 'personnel_management_recruitment',
                                eventProps: {
                                    click_context: data.dutyName
                                }
                            });
                        }}
                    >
                        <strong style={{ padding: '0 8px' }}>{applyNum}</strong>
                    </Link>
                    份
                </Col>
                <Col style={{ marginRight: 16 }}>
                    人才库
                    <Link
                        to={mixinBasePath({ activeKey: '2', notesSourceList: CHANNEL_CONDITION_FLAG_ENUM.RCK })}
                        onClick={() => {
                            eventTrack({
                                eventName: 'personnel_management_recruitment_demand_list_talent_num_click',
                                pageName: 'personnel_management_recruitment',
                                eventProps: {
                                    click_context: data.dutyName
                                }
                            });
                        }}
                    >
                        <strong style={{ padding: '0 8px' }}>{recruitNumFromTalent}</strong>
                    </Link>
                    份
                </Col>

                <AuthComponent code="office:recruitment:channel">
                    <Col>
                        发布情况 ：外部 ({renderPopoverNum(releaseOutwardChannelNameList, outChannelReleaseNum)}/
                        {totalOutwardNum}) 个 / 内部 (
                        {renderPopoverNum(releaseInnerChannelNameList, innerChannelReleaseNum)}/{totalInwardNum})个
                    </Col>
                </AuthComponent>
            </Row>
            {renderBtn()}
        </Row>
    );

    return (
        <>
            <ListItem content={content} action={action} />
        </>
    );
}

export default connect(({ user }) => ({ user: user.currentUser }))(Form.create()(DemandItem));
